<template>
  <view @touchmove.stop.prevent>
    <!-- 评论弹窗 -->
    <u-popup
	    :show="show" 
      mode="bottom"
      :round="10"
      :closeable="true"
      :safe-area-inset-bottom="true"
	    @close="close"
    >
      <view class="popup-container">
        <!-- 弹窗标题 -->
        <view class="popup-header">
          <text class="title">评论（{{commentCount || 0}}）</text>
        </view>
        
        <!-- 评论列表 -->
        <scroll-view class="comment-list" scroll-y @scrolltolower="moreCommentList">
          <comment 
            :commentList="commentList" 
            :showRepply="true"
            @reply="handleReply"
          />
        </scroll-view>
        
        <!-- 输入框区域 -->
        <view class="input-area">
          <input
            v-model="commentContent"
            class="comment-input"
            placeholder="说些什么吧..."
            placeholder-class="placeholder"
          />
          <view class="icon-group">
            <image :src="$util.img('image/sanqi/ping_2.png')" class="icon" @click="addImg()"/>
			      <view class="send" @click="submitComment">发送</view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import comment from '@/components/comment/comment.vue';

export default {
  name: "commentPop",
  components: {
    comment
  },
  props: {
		show: {
			type: Boolean,
			default: false
		},
    articleId: {
      type: [Number, String],
      default: 0
    },
    commentType: {
      type: String,
      default: '',   // 评论类型，默认为文章评论，可选值为：'article', 'activity（活动评论）'
    }
	},
  data() {
    return {
      commentList: [],   // 评论列表
      page: 1,
      commentContent: '',
      imgList: [],   // 图片列表
      parent_id: 0,   // 回复的评论id
      top_parent_id: 0,   // 最顶层评论的id
      commentCount: 0,   // 总评论数
    };
  },
  created() {
    this.getCommentList();
  },
  methods: {
    // 关闭弹窗
    close() {
       this.$emit('close', false);
    },
    //上传图片
    addImg() {
      let size = this.imgList.length ? this.imgList.length : 0
				this.$util.upload(3, {}, res => {
					this.imgList = this.imgList.concat(res);
				});
    },
    // 处理回复点击
    handleReply(data) {
      this.parent_id = data.parent_id;
      this.top_parent_id = data.top_parent_id;
      this.commentContent = `回复 ${data.parent_id ? data.parent_nickname : '@'+data.top_parent_nickname+' '}`+':' +' ' ;
    },
    
    // 提交评论
    submitComment() {
      if (this.commentContent.trim()) {
        if(this.top_parent_id !== 0) {
          // 按照冒号拆分输入框内容，取后面部分内容
          this.commentContent = this.commentContent.split(':')[1];
          if (!this.commentContent.trim()) {
            return uni.showToast({
              title: '请输入评论内容',
              icon: 'none'
            });
          }
        }
      }else {
        uni.showToast({
          title: '请输入评论内容',
          icon: 'none'
        });
        return;
      }

      var params = {
        content: this.commentContent,
        image: this.imgList.length ? this.imgList.join(',') : '',
        parent_id: this.parent_id || 0,
        top_parent_id: this.top_parent_id || 0
      };

      if(this.commentType === 'activity') {
        params.goods_id = this.articleId;
      }else {
        params.article_id = this.articleId;
      }
      
      this.$api.sendRequest({
        url: this.commentType === 'activity' ? '/api/subscribegoodscomment/add' : "/api/communityarticlecomment/add",
        data: params,
        success: res => {
          if (res.code === 0) {
            uni.showToast({
              title: '评论成功',
              icon: 'success'
            });
            this.commentContent = '';
            this.imgList = [];
            this.parent_id = 0;
            this.top_parent_id = 0;
            this.page = 1;
            this.getCommentList();
          } else {
            uni.showToast({
              title: res.message,
              icon: 'none'
            });
          }
        }
      });
    },
    //获取文章的评论列表
      getCommentList() {
        var params = {
          page: this.page,
        };
        if(this.commentType === 'activity') {
          params.goods_id = this.articleId;
        }else {
          params.article_id = this.articleId;
        }
      
        this.$api.sendRequest({
          url: this.commentType === 'activity' ? '/api/subscribegoodscomment/page' : "/api/communityarticlecomment/page",
          data: params,
          success: res => {
            if(res.code == 0) {
              this.commentCount = res.data.comment_count;
              if(this.page == 1) this.commentList = [];
              this.commentList = [...this.commentList, ...res.data.list];

              // 数组双层循环，先循环评论，将评论中的图片字符串逗号分隔，转为数组，再循环回复，将回复中的图片字符串逗号分隔，转为数组
              this.commentList.forEach(item => {

                if (item.image) {
                  // 先判断有没有逗号，如果有就分隔为数组
                  if (item.image.indexOf(',') > -1) {
                    item.image = item.image.split(',')
                  }else {
                    item.image = [item.image]
                  }
                }

                if (item.child && item.child.length > 0) {
                  item.child.forEach(reply => {
                    if (reply.image) {
                      // 先判断有没有逗号，如果有就分隔为数组
                      if (reply.image.indexOf(',') > -1) {
                        reply.image = reply.image.split(',')
                      }else {
                        reply.image = [reply.image]
                      }
                    }
                  })
                }

              })

              this.$forceUpdate();
              
            }else {
              this.$util.showToast({title: res.message})
            }
          }
        })
      },
    moreCommentList() {
      this.page++;
      this.getCommentList();
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-container {
  padding: 30rpx;
  height: 70vh;
  display: flex;
  flex-direction: column;
  border-radius: 20rpx;
  
  .popup-header {
    padding-bottom: 20rpx;
	display: flex;
	justify-content: center;
	align-items: center;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #131A33;
    }
  }
  
  .comment-list {
    flex: 1;
    overflow-y: auto;
    padding: 20rpx 0;
  }
  
  .input-area {
    display: flex;
    align-items: center;
    padding-top: 20rpx;
    border-top: 1rpx solid #f5f5f5;
    
    .comment-input {
      flex: 1;
      height: 72rpx;
      background-color: #F7F7F7;
      border-radius: 36rpx;
      padding: 0 28rpx;
      font-size: 28rpx;
      margin-right: 20rpx;
    }
    
    .placeholder {
      color: #B8BAC2;
      font-size: 26rpx;
    }
    
    .icon-group {
      display: flex;
      align-items: center;
      
      .icon {
        width: 48rpx;
        height: 48rpx;
        margin-right: 20rpx;
      }
	  .send {
		background: $color-title2;
		color: #fff;
		font-size: 24rpx;
		border-radius: 40rpx;
		padding: 10rpx 40rpx;
	  }
    }
  }
}
</style>